package com.zhong.gang.pda.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import android.zyapi.CommonApi;
import android.zyapi.Conversion;

import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;
import java.security.InvalidParameterException;
import java.util.Objects;

import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortTool;

public class PowerUtil {

    public static final String PATH = "/dev/ttyS1";
    public static final int BAUTRATE = 9600;

    protected SerialPortTool serialPortTool;
    protected SerialPort mSerialPort;
    protected OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;

    private Activity activity;
    private PowerUtilListener listener;

    public PowerUtil(Activity activity, PowerUtilListener listener) {
        this.activity = activity;
        this.listener = listener;
    }

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (true) {
                int size;
                try {
                    byte[] buffer = new byte[64];
                    if (mInputStream == null) {
                        return;
                    }
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        onDataReceived(buffer, size);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }


    private void DisplayError(String resourceId) {
        AlertDialog.Builder b = new AlertDialog.Builder(activity);
        b.setTitle("串口异常");
        b.setMessage(resourceId);
        b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Log.e("==``", "报错啦" + resourceId);
            }
        });
        b.show();
    }

    /**
     * 设置串口
     *
     * @param id
     */
    public void power(String id) {

        CommonApi mCommonApi = new CommonApi();
        mCommonApi.setGpioDir(27, 0);
        mCommonApi.getGpioIn(27);

        new Handler().postDelayed(() -> {
            // TODO Auto-generated method stub
            mCommonApi.setGpioMode(27, 0);
            mCommonApi.setGpioDir(27, 1);
            int ret = mCommonApi.setGpioOut(27, 1);
            Log.d("commonApi",String.valueOf(ret));
        }, 1000);
    }

    /**
     * 打开
     *
     * @return
     */
    public boolean open() {
        boolean bret = false;
        if (serialPortTool == null) {
            serialPortTool = new SerialPortTool();
        }

        try {
            mSerialPort = serialPortTool.getSerialPort(PATH, BAUTRATE);
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();

            /* Create a receiving thread */
            if (mReadThread == null) {
                mReadThread = new ReadThread();
                mReadThread.start();
            }
            bret = true;
        } catch (SecurityException e) {
            DisplayError("你没有读写权限");
            Log.e("==``", "报异常open----" + e.toString());
        } catch (IOException e) {
            DisplayError("由于未知原因，串口不能打开");
            Log.e("==``", "报异常open----" + e.toString());
        } catch (InvalidParameterException e) {
            DisplayError("请先配置串口");
            Log.e("==``", "报异常open----" + e.toString());
        } catch (Exception e) {
            DisplayError("由于未知原因，串口不能打开");
            Log.e("==``", "报异常open----" + e.toString());
        }

        return bret;
    }

    /**
     * 关闭
     */
    public void close() {
        if (mReadThread != null) {
            mReadThread.interrupt();
            mReadThread = null;
        }
        if (serialPortTool != null) {
            serialPortTool.closeSerialPort();
        }
        mSerialPort = null;
    }


    protected void onDataReceived(final byte[] buffer, final int size) {
        // TODO Auto-generated method stub
        activity.runOnUiThread(new Runnable() {
            public void run() {
                Log.d("数据输出", "获取到数据长度：" + size);
                if (size >= 6) {
                    byte[] tempBuf = new byte[size - 2];
                    System.arraycopy(buffer, 2, tempBuf, 0, size - 2);//discard 4 bit
                    String strRead = Conversion.Bytes2HexString(tempBuf);
//          String temStr = new String( tempBuf );
//          int temInt = Integer.parseInt( temStr, 16 );
                    Long temInt = 0L;
                    try {
                        temInt = Long.parseLong(strRead, 16);
                    } catch (Exception e) {
                        Log.d("串口解析错误", Objects.requireNonNull(e.getMessage()));
                    }
                    String rfid_data = String.format("%010d", temInt);
                    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone rt = RingtoneManager.getRingtone(activity, uri);
                    rt.play();
                    String str1 = rfid_data;
                    for (int i = 0; i < buffer.length; i++) {
                        str1 += buffer[i];
                    }
                    if (listener != null) {
                        String cardNo = str1.substring(0, 10);
                        Log.e("==``", cardNo);
                        listener.onDataReceived(cardNo);
                    }
                }
            }
        });
    }

    public interface PowerUtilListener {
        void onDataReceived(String str);
    }
}
